import * as path from 'path';

const fs = require('fs');


/**
 * 文件夹工具类
 * @author Zhang
 * @date 2019年1月31日17:46:52
 */
export class DirectoryUtils {

  /**
   * 读取目录
   * @param {string} dir 目录路径
   * @param {function} handler 读到文件时的处理函数
   * @param {string[]} [excludes] 排除的目录
   */
  static readDir(dir: string, handler: (path: string) => void, excludes: string[] = null) {
    const controllerFiles = fs.readdirSync(dir);
    if (controllerFiles) {
      for (const file of controllerFiles) {
        if (excludes && excludes.includes(file)) {
          continue;
        }
        const filePath = dir + file;
        if (fs.statSync(filePath).isDirectory()) {
          // 递归扫描文件
          this.readDir(filePath + path.sep, handler);
          continue;
        }
        handler(filePath);
      }
    }
  }

  /**
   * 异步扫描文件夹
   * @param dir 文件夹
   * @param handler 文件处理回调
   * @param [excludes] 要排除的目录
   */
  static readDirAsync(dir: string, handler: (path: string) => void, excludes: string[] = null): Promise<any[]> {
    const read = (basePath) => {
      let handlers = [];

      const controllerFiles = fs.readdirSync(basePath);
      if (controllerFiles) {
        for (const file of controllerFiles) {
          if (excludes && excludes.includes(file)) {
            continue;
          }
          const filePath = basePath + file;
          if (fs.statSync(filePath).isDirectory()) {
            // 递归扫描文件
            handlers = [...handlers, ...(read(filePath + path.sep))];
            continue;
          }
          handlers.push(handler(filePath));
        }
      }
      return handlers;
    };

    return Promise.all(read(dir));
  }

}
